<script setup lang="ts">
import { useRouter } from "vue-router";
import { io, Socket } from "socket.io-client";
import { ref, Ref, onMounted } from "vue";
import { get, post } from "@/request";
const user = JSON.parse(localStorage.getItem("user") || "[]");
const user2 = JSON.parse(localStorage.getItem("user2") || "[]");
// let roomId = `room_${Date.now()}_${user._id}_${user2._id}`;
let roomId = "room_1697186399120_1_2";
console.log(JSON.stringify(localStorage.getItem("json")));
let websocket = ref<Socket | null>(null); // WebSocket 实例，可以是 null
let called = ref<boolean>(false); //是否是接收方
const caller = ref<boolean>(false); //是否是发起方
const flag = ref<boolean>(true); //是否是发起方
const callers = ref<boolean>(false); //是否是发起方
const calleds = ref<boolean>(false); //是否是发起方
const calling = ref<boolean>(false); //呼叫中
const communicating = ref<boolean>(false); //视频通话中
const localVideo = ref<HTMLVideoElement | null>(null); //video标签实例，播放本人的视频
const remoteVideo = ref<HTMLVideoElement | null>(null); // video标签实例，播放对方的视频
let peer = ref(null) as any; // RTCPeerConnection 实例，可以是 null
let localStream = ref<any>(); // MediaStream 实例，可以是 null``
onMounted(() => {
  let socket = io("localhost:3000");
  socket.on("connectionSuccess", (socket) => {
    console.log("连接成功:");
  });
  socket.emit("joinRoom", roomId);
  socket.on("callRemote", (socket) => {
    if (!caller.value) {
      called.value = true; //呼叫方
      calleds.value = true; //呼叫方
      callers.value = true; //呼叫方
      flag.value = true;
      calling.value = true;
      calleds.value = true;
    }
  });
  socket.on("acceptCall", async () => {
    if (caller.value) {
      peer.value = new RTCPeerConnection();
      peer.value.addStream && peer.value.addStream(localStream.value);
      peer.value.onicecandidate = (event: any) => {
        if (event.candidate) {
          console.log("用户A获取candidate信息", event.candidate);
          socket.emit("sendCandidate", { roomId, candidate: event.candidate });
        }
      };

      peer.value.onaddstream = (event: any) => {
        console.log("用户A收到用户B的stream", event.stream);
        calling.value = false;
        communicating.value = true;
        remoteVideo.value!.srcObject = event.stream;
        remoteVideo.value!.play();
      };
      let offer = await peer.value.createOffer({
        offerToReceiveAudio: 1,
        offerToReceiveVideo: 1,
      });
      console.log("offer", offer);
      await peer.value.setLocalDescription(offer);
      socket.emit("sendOffer", { offer, roomId });
    }
  });

  socket.on("sendOffer", async (offer) => {
    if (called.value) {
      console.log("收到offer", offer);
      peer.value = new RTCPeerConnection();
      const stream = await getLocalstream();
      peer.value.addStream && peer.value.addStream(stream);
      peer.value.onicecandidate = (event: any) => {
        if (event.candidate) {
          console.log("用户B获取candidate信息", event.candidate);
          socket.emit("sendCandidate", { roomId, candidate: event.candidate });
        }
      };
      peer.value.onaddstream = (event: any) => {
        console.log("用户B收到用户A的stream", event.stream);
        calling.value = false;
        communicating.value = true;
        remoteVideo.value!.srcObject = event.stream;
        remoteVideo.value!.play();
      };
      await peer.value.setRemoteDescription(offer);
      let answer = await peer.value.createAnswer();
      console.log("用户B生成answer", answer);
      await peer.value.setLocalDescription(answer);
      socket.emit("sendAnswer", { answer, roomId });
    }
  });
  socket.on("sendAnswer", async (answer) => {
    if (caller.value) {
      await peer.value.setRemoteDescription(answer);
    }
  });
  socket.on("sendCandidate", async (candidate) => {
    console.log("收到candidate信息", candidate);
    await peer.value.addIceCandidate(candidate); // 用户A和用户B分别收到candidate后，都添加到自己的peer对象上
    await peer.value.addCandidate(candidate);
  });
  socket.on("hangUp", () => {
    rest();
  });
  websocket.value = socket;
});
const callRemote = async () => {
  console.log("发起视频");
  //用户A向用户B发送请求
  callers.value = true;
  caller.value = true;
  callers.value = true;
  calling.value = true;
  await getLocalstream();
  websocket.value!.emit("callRemote", roomId);
};
const acceptCall = () => {
  console.log("同意视频");
  websocket.value!.emit("acceptCall", roomId);
};

const hangup = () => {
  calleds.value = false;
  callers.value = false;
  // calling.value = false;
  console.log("挂断视频");
  websocket.value!.emit("hangUp", roomId);
};
const rest = () => {
  calling.value = false;
  called.value = false;
  calleds.value = false;
  callers.value = false;
  flag.value = false;
  communicating.value = false;
  peer.value = null;
  localStream.value = null;
  localVideo.value!.srcObject = null;
  remoteVideo.value!.srcObject = null;
};
const getLocalstream = async () => {
  const stream = await navigator.mediaDevices.getUserMedia({
    audio: true,
    video: true,
  });
  localVideo.value!.srcObject = stream;
  localVideo.value!.play();
  localStream.value = stream;
  return stream;
};
let Talks = ref([]);
onMounted(() => {
  getDate();
});
const content = ref("");
const addMassage = (product = null) => {
  let data = {
    senderId: JSON.parse(localStorage.getItem("user"))._id,
    message: content.value,
    senderId2: JSON.parse(localStorage.getItem("user2"))._id,
    product: null,
  };
  websocket.value!.emit("private_message", data);
  post("/addNews", data);
  content.value = "";
  getDate();
};
const item = JSON.parse(localStorage.getItem("json") as string);
let getDate = () => {
  const user1Id = JSON.parse(localStorage.getItem("user") || "{}")._id || "";
  const user2Id = JSON.parse(localStorage.getItem("user2") || "{}")._id || "";

  if (!user1Id || !user2Id) {
    console.error("User IDs are not available in localStorage.");
    return; // 可以选择返回或者采取其他错误处理方式
  }

  get(`getTalk/?user1=${user1Id}&user2=${user2Id}`)
      .then((res) => {
        console.log("Data retrieved successfully:", res);
        Talks.value = res.data;
      })
      .catch((error) => {
        console.error("Error fetching talk data:", error);
        // 在这里处理错误，比如显示错误信息给用户或者进行其他恢复操作
      });
};
const expression = ref([
  { name: "😀", value: "1f600" },
  { name: "😁", value: "1f601" },
  { name: "😂", value: "1f602" },
  { name: "🤣", value: "1f923" },
  { name: "😃", value: "1f603" },
  { name: "😄", value: "1f604" },
  { name: "😅", value: "1f605" },
  { name: "😆", value: "1f606" },
  { name: "😉", value: "1f609" },
  { name: "😊", value: "1f60a" },
  { name: "😋", value: "1f60b" },
  { name: "😎", value: "1f60e" },
  { name: "😍", value: "1f60d" },
  { name: "😘", value: "1f618" },
  { name: "😗", value: "1f617" },
  { name: "😙", value: "1f619" },
  { name: "😚", value: "1f61a" },
  { name: "😋", value: "1f60b" },
  { name: "😛", value: "1f61b" },
  { name: "😜", value: "1f61c" },
  { name: "😝", value: "1f61d" },
  { name: "🤨", value: "1f928" },
  { name: "🤩", value: "1f929" },
  { name: "🥰", value: "1f970" },
  { name: "😏", value: "1f60f" },
  { name: "😶", value: "1f610" },
  { name: "😐", value: "1f611" },
  { name: "😑", value: "1f612" },
  { name: "😒", value: "1f613" },
  { name: "🙄", value: "1f615" },
  { name: "😬", value: "1f625" },
  { name: "🤥", value: "1f926" },
  { name: "😌", value: "1f60c" },
  { name: "😔", value: "1f61f" },
  { name: "😕", value: "1f623" },
  { name: "🙃", value: "1f643" },
  { name: "😖", value: "1f616" },
  { name: "😞", value: "1f61e" },
  { name: "😟", value: "1f61d" },
  { name: "😤", value: "1f624" },
]);

const router = useRouter();
const constor = (name) => {
  content.value += " " + name;
  console.log(content.value);
};
const flags = ref(false);
const flagchange = () => {
  flags.value = !flags.value;
};
</script>

<template>
  <div class="w-100% h-20px flex items-center z-[1000] justify-between">
    <div class="flex">
      <van-icon
          @click="router.push('/home/message')"
          class="mt-2"
          size="24"
          name="arrow-left"
      />
      <p class="leading-10 ml-2">{{ user2.name }}</p>
    </div>
    <div>
      <van-icon @click="callRemote" name="phone-o" size="32" class="mx-2" />
      <van-icon name="list-switch" size="32" class="mx-1" />
    </div>
  </div>
  <div class="" v-for="item in Talks" :key="item._id">
    <div class="h-20 w-[100%]" v-if="item.senderId === user._id">
      <div class="float-end flex">
        <p class="leading-[70px] mr-5">{{ item.message }}</p>
        <img class="w-14 h-14 rounded-full" :src="user.avatar" alt="" />
      </div>
    </div>
    <div class="flex mt-5" v-else>
      <img class="w-14 h-14 rounded-full" :src="user2.avatar" alt="" />
      <p class="leading-[70px] ml-5">{{ item.message }}</p>
    </div>
  </div>

  <div
      v-if="callers || calleds"
      class="w-[100%] h-[102vh] fixed top-0 flex items-center flex-col text-center h-screen"
  >
    <div class="relative h-full mb-4 fBox">
      <video
          ref="localVideo"
          class="w-[100%] h-full bg-gray-200 mb-4 object-cover"
      ></video>
      <video
          ref="remoteVideo"
          class="w-32 h-48 absolute top-0 right-0 object-cover"
      ></video>
      <div
          v-if="caller && calling"
          class="absolute top-2/3 left-36 flex flex-col items-center"
      >
        <p class="mb-4 text-white">等待对方接听...</p>
        <img @click="hangup" src="/gd.svg" class="w-20 cursor-pointer" alt="" />
      </div>
      <div
          v-if="(callers && calling == false) || (calleds && calling == false)"
          class="absolute top-2/3 ml-52 flex flex-col items-center"
      >
        <img @click="hangup" src="/gd.svg" class="w-20 cursor-pointer" alt="" />
      </div>
      <div
          v-if="called && calling"
          class="absolute top-2/3 left-32 flex flex-col items-center"
      >
        <p class="mb-4 text-white">收到视频邀请...</p>
        <div class="flex">
          <img
              @click="hangup"
              src="/gd.svg"
              class="w-20 cursor-pointer mr-4"
              alt=""
          />
          <img
              @click="acceptCall"
              src="/jt.svg"
              class="w-20 cursor-pointer"
              alt=""
          />
        </div>
      </div>
    </div>
  </div>

  <div>
    <div
        v-if="!calling && !called && !callers"
        class="bg-white w-[100%] fixed bottom-0"
    >
      <div class="w-100% flex items-center justify-evenly">
        <input
            v-model="content"
            type="text"
            class="w-[70%] border-2 h-10"
            placeholder="输入想说的话...."
        />
        <van-button type="primary" @click="addMassage">发送</van-button>
      </div>
      <div class="w-96 items-center justify-evenly mx-auto mt-2">
        <van-icon name="volume-o" size="28" class="mx-4" />
        <van-icon name="photo-o" size="28" class="mx-4" />
        <van-icon name="video-o" size="28" class="mx-4" />
        <van-icon name="bill-o" size="28" class="mx-4" />
        <van-icon name="smile-o" size="28" class="mx-4" @click="flagchange" />
        <van-icon name="add-o" size="28" class="mx-4" />
      </div>
      <div v-if="flags" class="w-[100vw] m-5 h-[200px] flex flex-wrap">
        <div
            v-for="item in expression"
            :key="item.value"
            @click="constor(item.name)"
            class="w-10 h-10"
        >
          {{ item.name }}
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
</style>